package com.sl.au.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventRegisterAndTaskView;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.Option;
import com.sl.au.entity.User;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

@RestController
@RequestMapping("/ui/underTimeout")
public class UnderTimeOutController extends BaseController {

	@Autowired
	private EventRegisterService eventRegisterService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private EventReportService eventReportService;
	@Autowired
	private OperateLogService operateLogService;

	@RequestMapping("/getProcedure/{reportId}")
	public MsgHelper getProcedure(@PathVariable("reportId") String reportId) {
		List<EventTask> procedures = eventReportService.findProcedures(reportId);
		return MsgHelper.success().put("procedures", procedures);
	}

	@RequestMapping("/sendAllMessage")
	public MsgHelper sendAllMessage() {
		// 全部已超时事件

		Option option = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "处理中").get(0);

		Option limitOpt = optionService.getRepository().findByGroupAndTitle("超时时限", "处理中").get(0);
		double limit = 0.5;// 默认时限
		if (limitOpt != null) {
			limit = ExdeUtil.str2double(limitOpt.getValue());
		}

		List<EventRegisterAndTaskView> all = eventRegisterService.findUnderTimeoutEventNew(0, Integer.MAX_VALUE, "",
				limit, option);
		if (all.size() == 0) {
			return MsgHelper.success().put("msg", "没有处理即将超时的事件");
		} else {
			for (EventRegisterAndTaskView ev : all) {
				String registerId = ev.getRegister().getId();
				sendMessageToOne(registerId);
			}
			return MsgHelper.success().put("msg", "成功发送 " + all.size() + " 条信息");
		}
	}

	@RequestMapping("/sendMessage/{registerId}")
	public MsgHelper sendMessage(@PathVariable("registerId") String registerId) {

		sendMessageToOne(registerId);

		return MsgHelper.success();
	}

	private void sendMessageToOne(String registerId) {
		EventRegister register = eventRegisterService.getRepository().findOne(registerId);
		// 接收该事件的操作人
		if (register != null) {
			EventTask task = eventRegisterService.findTask(registerId, register.getRegisterEventState());
			String time = register.getCreateTime().toString();

			String phone = task.getEventTaskUser().getContactType();
			String content = "【悦来城市综合服务平台】您于[" + time + "]上报的[" + register.getRegisterEventName() + "]事件处理即将超时,请尽快处理!";
			Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "处理即将超时通知");
			if (op != null) {
				content = op.getTitle();
			}
			content = content.replace("{0}", time);
			content = content.replace("{1}", register.getRegisterEventName());
			Map<String, Object> mapTemp = this.sendMessage(phone, content);
			if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
				// 是否记录日志
				operateLogService.log(this.getMyAccount().getUser(), "处理即将超时通知", content);
			} else {
				operateLogService.log(this.getMyAccount().getUser(), "处理即将超时通知", "发送重复上报通知消息失败!");
			}
		}

	}

	@RequestMapping(value = "/initUnderTimeoutPage", method = RequestMethod.GET)
	public Map<String, Object> getpage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");

		Option option = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "处理中").get(0);

		Option limitOpt = optionService.getRepository().findByGroupAndTitle("超时时限", "处理中").get(0);
		double limit = 0.5;// 默认时限
		if (limitOpt != null) {
			limit = ExdeUtil.str2double(limitOpt.getValue());
		}

//		List<EventRegisterAndTaskView> infos = null;
//		int count = 0;
		// if (StringUtils.hasText(key)) {
		// infos = eventRegisterService.findUnderTimeoutEventByKey(start,
		// length, key, option);
		// count = eventRegisterService.findCountUnderTimeoutEventByKey(key,
		// option);
		// } else {
		// infos = eventRegisterService.findUnderTimeoutEvent(start, length,
		// option);
		// count = eventRegisterService.findCountUnderTimeoutEvent(option);
		// }
		
//		infos = eventRegisterService.findUnderTimeoutEventNew(start, length, key, limit, option);
//		count = eventRegisterService.findCountUnderTimeoutEventNew(key, limit, option);
		
		String roleId = this.getMyAccount().getRole().getId();
		List<Map<String,Object>> infos = null;
		int count = 0;
		
		infos = eventRegisterService.findUnderTimeoutEventByRole(start, length, roleId, key, limit, option, "createTime", "desc");
		count = eventRegisterService.findCountUnderTimeoutEventByRole(roleId, key, limit, option);
		
		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		modelAndView = createLayoutView("underTimeOut/index");
		return modelAndView;
	}

}
